<?php defined('BASEPATH') OR exit('No direct script access allowed');


class WS_model extends CI_Model
{
    var $cacheOffRequest = false;
    var $is_cache_on;

    public function __construct()
    {
        parent::__construct();
        $this->is_cache_on = $this->db->cache_on;
    }

    public function cacheOff()
    {
        $this->cacheOffRequest = true;
    }

    public function ShutDownCache()
    {
        if ($this->is_cache_on && $this->cacheOffRequest)
            $this->db->cache_off();
    }

    public function turnOnCache()
    {
        if ($this->is_cache_on && $this->cacheOffRequest)
            $this->db->cache_on();
        $this->cacheOffRequest = false;
    }

    public function eachDay_newCache()
    {
        $this->db->where('\'' . date('y-m-d H') . '\' = \'' . date('y-m-d H') . '\'');
    }

    public function result()
    {
        $this->eachDay_newCache();
        $this->ShutDownCache();
        $query = $this->db->get();
        $this->turnOnCache();
        if ($query->num_rows())
            return $query->result();
        return false;
    }

    public function result_array()
    {
        $this->eachDay_newCache();
        $this->ShutDownCache();
        $query = $this->db->get();
        $this->turnOnCache();
        if ($query->num_rows())
            return $query->result_array();
        return false;
    }

    public function row()
    {
        $this->eachDay_newCache();
        $this->ShutDownCache();
        $query = $this->db->get();
        $this->turnOnCache();
        if ($query->num_rows())
            return $query->row();
        return false;
    }

    public function count()
    {
        $this->eachDay_newCache();
        $this->ShutDownCache();
        $return = $this->db->count_all_results();
        $this->turnOnCache();
        return $return;
    }

    public function insert_path_single_($insert_id, $category_id)
    {
        $this->db->select("$insert_id, ancestor");
        $this->db->from('closures');
        $this->db->where('descendant', ($category_id ? $category_id : 0));
        $sql = $this->sql();
        $query = 'INSERT INTO {PRE}wallpapers_path (wallpaper_seq_id, category_seq_id) ' . $sql . '';
        $this->db->query($query);
    }

    public function removeWallpaperPath_($wall_id)
    {
        $this->db->delete('wallpapers_path', array('wallpaper_seq_id' => $wall_id));
        return $this->db->affected_rows();
    }

    public function sql($eachDay = false)
    {
        if ($eachDay)
            $this->eachDay_newCache();
        return $this->db->return_query();
    }

    public function sql_md5()
    {
        return md5($this->sql(true));
    }

    public function wallpaperTemplate($select = true, $type = 'normal', $options = array())
    {
        $tags = isset($options['tag']) ? $options['tag'] : false;
        $colors = isset($options['colors']) ? $options['colors'] : false;
        $category_sql = $this->wallCatTemplate();
        $tag_sql = $this->wallTagsTemplate();
        $download_sql = $this->wallpaperDownloads();
        $views_sql = $this->wallpaperViews();
        $favourites_sql = $this->wallpaperFavourite();
        $count = isset($options['count']) ? $options['count'] : false;

        $vote_sql = $this->wallVotes();
        $tag_view_sql = $this->tag_view_sql($tags);

        if ($colors)
            $colorPath_sql = $this->color_sql($colors);

        if ($select)
            $this->db->select('w.*,c.*,u.user_name,u.user_email,t.tags,d.total_downloads,v.total_views,f.total_favourites,vo.vote_up,vo.vote_down');

        switch ($type) {
            case'by_user_downloads':
                $this->db->from('(SELECT * FROM {PRE}wallpapers_downloads where wd_uid = ' . $options['by_user_downloads'] . ' GROUP by wd_wid) bud');
                $this->db->join('wallpapers w', 'w.wallpaper_seq_id = bud.wd_wid');
                $this->db->join("($category_sql) as c", 'c.category_seq_id = w.category_seq_id', 'left');
                break;
            case'by_user_favourites':
                $this->db->from('(SELECT * FROM {PRE}wallpapers_favourites where wf_uid = ' . $options['by_user_favourites'] . ') buf');
                $this->db->join('wallpapers w', 'w.wallpaper_seq_id = buf.wf_wid');
                $this->db->join("($category_sql) as c", 'c.category_seq_id = w.category_seq_id', 'left');
                break;
            case'by_user_likes':
                $this->db->from('(SELECT * FROM {PRE}wallpapers_votes where vote_uid = ' . $options['by_user_likes'] . ' AND vote_up = 1) bul');
                $this->db->join('wallpapers w', 'w.wallpaper_seq_id = bul.vote_wid');
                $this->db->join("($category_sql) as c", 'c.category_seq_id = w.category_seq_id', 'left');
                break;
            case'by_user_dislikes':
                $this->db->from('(SELECT * FROM {PRE}wallpapers_votes where vote_uid = ' . $options['by_user_dislikes'] . ' AND vote_down = 1) bul');
                $this->db->join('wallpapers w', 'w.wallpaper_seq_id = bul.vote_wid');
                $this->db->join("($category_sql) as c", 'c.category_seq_id = w.category_seq_id', 'left');
                break;
            case'bypath':
                $this->db->from('wallpapers_path wp');
                $this->db->join('wallpapers w', 'w.wallpaper_seq_id = wp.wallpaper_seq_id');
                $this->db->join("($category_sql) as c", 'c.category_seq_id = wp.category_seq_id', 'left');
                break;
            case'color':
                $this->db->select('wc.*');
                $this->db->from('(' . $colorPath_sql . ') wc');
                $this->db->join('wallpapers w', 'w.wallpaper_seq_id = wc.wallpaper_seq_id');
                $this->db->join("($category_sql) as c", 'c.category_seq_id = w.category_seq_id', 'left');
                break;
            case 'tag':
                $this->db->from('(' . $tag_view_sql . ') wt');
                $this->db->join('wallpapers w', 'w.wallpaper_seq_id = wt.wallpaper_seq_id');
                $this->db->join("($category_sql) as c", 'c.category_seq_id = w.category_seq_id', 'left');
                break;
            case'normal':
                $this->db->from('wallpapers w');
                $this->db->join("($category_sql) as c", 'c.category_seq_id = w.category_seq_id', 'left');
                break;
        }

        if (!$count) {
            $this->db->join('user u', 'u.user_seq_id = w.user_seq_id', 'left');
            $this->db->join("($tag_sql) as t", 't.tag_w_id = w.wallpaper_seq_id', 'left');
            $this->db->join("($download_sql) as d", 'd.wd_wid = w.wallpaper_seq_id', 'left');
            $this->db->join("($views_sql) as v", 'v.wv_wid = w.wallpaper_seq_id', 'left');
            $this->db->join("($favourites_sql) as f", 'f.wf_wid = w.wallpaper_seq_id', 'left');
            $this->db->join("($vote_sql) as vo", 'vo.vote_wid = w.wallpaper_seq_id', 'left');
        }
    }

    public function color_sql($filter)
    {
        $this->db->select('*,sum(count) AS color_sum');
        $this->db->from('wallpapers_colors');
        $this->db->where('saturation BETWEEN ' . (($filter['saturation'][0]) / 100) . ' AND ' . (($filter['saturation'][1]) / 100));
        $this->db->where('lightness BETWEEN ' . (($filter['lightness'][0]) / 100) . ' AND ' . (($filter['lightness'][1]) / 100));
        $this->db->where('hue BETWEEN ' . ($filter['hue'][0]) . ' AND ' . ($filter['hue'][1]));
        $this->db->group_by('wallpaper_seq_id');
        return $this->sql();
    }

    public function wallVotes()
    {
        $this->db->select('sum(vote_up) AS vote_up,sum(vote_down) AS vote_down,vote_wid');
        $this->db->from('wallpapers_votes');
        $this->db->group_by('vote_wid');
        return $this->sql();
    }

    public function tag_view_sql($keyword)
    {
        $this->db->from('wallpapers_tags');
        $this->db->where('LOWER(tag_name)', strtolower($keyword));
        return $this->sql();
    }

    public function wallCatTemplate($return_sql = true)
    {
        $this->db->select("t2.*, GROUP_CONCAT(c.category_slug order by c1.lvl desc SEPARATOR '/') AS cFullSlug, GROUP_CONCAT(c.category_name order by c1.lvl desc SEPARATOR '|') AS cFullName");
        $this->db->from('closures c1');
        $this->db->join('category c', 'c.category_seq_id = c1.ancestor', 'left');
        $this->db->join('category t2', 't2.category_seq_id = c1.descendant', 'left');
        $this->db->group_by('c1.descendant');
        if ($return_sql)
            return $this->sql();
    }

    public function wallTagsTemplate()
    {
        $this->db->select("wallpaper_seq_id as tag_w_id, group_concat(tag_name SEPARATOR ',') as tags");
        $this->db->from('wallpapers_tags');
        $this->db->group_by('wallpaper_seq_id');
        return $this->sql();
    }

    public function wallpaperDownloads()
    {
        $this->db->select('count(*) AS total_downloads, wd_date, wd_ip, wd_uid, wd_wid');
        $this->db->from('wallpapers_downloads');
        $this->db->group_by('wd_wid');
        return $this->sql();
    }

    public function wallpaperViews()
    {
        $this->db->select('count(*) AS total_views, wv_date, wv_ip, wv_uid, wv_wid');
        $this->db->from('wallpapers_views');
        $this->db->group_by('wv_wid');
        return $this->sql();
    }

    public function wallpaperFavourite()
    {
        $this->db->select('count(*) AS total_favourites, wf_date, wf_ip, wf_uid, wf_wid');
        $this->db->from('wallpapers_favourites');
        $this->db->group_by('wf_wid');
        return $this->sql();
    }

    public function wallpaperColors()
    {
        $this->db->select("wallpaper_seq_id AS wid,GROUP_CONCAT(count, '|', hex_code ORDER BY count desc) AS colors", false);
        $this->db->from('wallpapers_colors');
        $this->db->where('count !=', '0.000000000000000');
        $this->db->group_by('wallpaper_seq_id');
        return $this->sql();
    }

    public function is_global_wallpaper_set()
    {
        return $this->session->userdata('GLOBAL') && $this->session->userdata('SCREEN_SIZE') && !$this->config->item('is_administrator');
    }

    public function global_wallpaper()
    {
        if ($this->is_global_wallpaper_set()) {
            $screen_size = $this->session->userdata('SCREEN_SIZE');
            if ($screen_size['width'] && $screen_size['height']) {
                $this->db->where('w.wallpaper_width >=', $screen_size['width']);
                $this->db->where('w.wallpaper_height >=', $screen_size['height']);
            }
        }
    }
}